package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.DepartmentReposiroty;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentReposiroty departmentReposiroty;

    @Override
    public void save(Map<String, Object> paramMap) {
        //paramMap 转为对象
        String s = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(s, Department.class);


        Department tem =
                departmentReposiroty.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (tem != null) {
            tem.setUpdateTime(new Date());
            tem.setIsDeleted(0);
            departmentReposiroty.save(tem);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentReposiroty.save(department);
        }
    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo vo) {
        Pageable pageable = PageRequest.of(page - 1, limit);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Department deps = new Department();
        BeanUtils.copyProperties(vo, deps);
        deps.setIsDeleted(0);
        Example<Department> dep = Example.of(deps, matcher);
        Page<Department> all = departmentReposiroty.findAll(dep, pageable);
        return all;
    }

    /**
     * 删除科室接口
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void remove(String hoscode, String depcode) {
        Department dep = departmentReposiroty.getDepartmentByHoscodeAndDepcode(hoscode, depcode);

        if (dep != null) {
            departmentReposiroty.deleteById(dep.getId());
        }

    }
}
